package com.tg.appcommon.android;
import android.os.Handler;

public abstract class HandlerTimer implements Runnable{
    protected Handler mHandler;
    private long mDelayMillis;
    private boolean mRepeat;

    public HandlerTimer(Handler handler) {
        mHandler = handler;
    }

    public final void start(long delayMillis, boolean repeat){
        mDelayMillis = delayMillis;
        mRepeat = repeat;
        if (mHandler != null){
            mHandler.removeCallbacks(this);
            mHandler.postDelayed(this, mDelayMillis);
        }
    }

    public void stop(){
        if (mHandler != null){
            mHandler.removeCallbacks(this);
            mRepeat = false;
        }
    }

    @Override
    public final void run() {
        try {
            onTimer();
        }catch (Exception e){
            e.printStackTrace();
        }
        if (mHandler != null){
            mHandler.removeCallbacks(this);
            if (mRepeat){
                mHandler.postDelayed(this, mDelayMillis);
            }
        }
    }

    public abstract void onTimer();
}
